//
//  LYUtil.m
//  LYLiveApp
//
//  Created by 徐琰璋 on 16/5/24.
//  Copyright © 2016年 览益信息科技. All rights reserved.
//

#import "LYUtil.h"
#import "AFNetworkReachabilityManager.h"
#import "MBProgressHUD.h"
#import "NSString+MD5.h"
#import "BBCodeParser.h"
#import "LYWebController.h"
#import "LYFeedBackController.h"
#import "LYArticleDetailController.h"
#import "LYTeacherHomePageController.h"
#import "LYAllTeacherController.h"
#import "LYMessageCenterController.h"
#import "LYLoginNewController.h"
#import <CoreText/CoreText.h>
#import "WatchPlayBackViewController.h"
#import "LYPlaybackModel.h"

#import "LYStockListController.h"
#import "LYHomeInforDetailController.h"
#import "LYSignInPopView.h"
#import "LYStockDetailController.h"
#import "LYMockDetailController.h"
#import "LYAppDelegate.h"
#import "LYNewQuotationController.h"
#import "LYNTESController.h"

#define kHUDColor RGBA(101, 101, 101, 0.96)

@implementation LYUtil

/**
 *  将null转换为@""
 *
 */
+(NSString *)nullEmpty:(NSString *)str {
    if ([str isKindOfClass:[NSNull class]]|| str == nil) {
        return @"";
    }else {
        return str;
    }
}

/**
 *  判断字符串是否为空
 *
 */

+ (BOOL)isNilOrEmpty:(NSString *)string
{
    if (string == nil || string == NULL) {
        return YES;
    }
    if ([string isKindOfClass:[NSNull class]]) {
        return YES;
    }
    if ([string isKindOfClass:[NSString class]] && [[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
        return YES;
    }
    return NO;
}
+ (BOOL)isArrayNilOrEmpty:(NSArray *)array
{
    if (array == nil) {
        return YES;
    }
    if ([array isKindOfClass:[NSArray class]]) {
        if (array.count >0) {
            return NO;
        }else{
            return YES;
        }
    }else{
        return YES;
    }
}

/**
 *   查看网络是否连接
 *
 *  @return YES 网络有连接  NO 网路断开
 */
+ (BOOL)hasNetwork{
    
    AFNetworkReachabilityManager *reachability = [AFNetworkReachabilityManager sharedManager];
    
    if (reachability.networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
        
//        [LYUtil showWarningHUD:kNoNetWorkMsg AddedTo:[[UIApplication sharedApplication] delegate].window interval:2.0];
        
        return NO;
    }
    
    
    return YES;
}

+(void) showProgressHUDAddedToVideoView:(UIView *)view{
    [LYUtil hideHUDTo:view];
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
    hud.color = [UIColor clearColor];
    [hud show:YES];
}
/**
 *  转菊花
 *
 *  @param view 父视图
 */
+(void) showProgressHUDAddedTo:(UIView *)view{
    
    [LYUtil hideHUDTo:view];
    
     MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
    hud.color = kHUDColor;
    
//    hud.mode = MBProgressHUDModeCustomView;
////    hud.color = HEX_RGBA(0x000000, 0.4);
//    hud.margin = 10;
//    hud.labelColor = RGBA(255, 255, 255, 1.0);
//    hud.labelFont = [UIFont systemFontOfSize:16];
//    hud.dimBackground = NO;
//    
//    UIView *waiting = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 60, 60)];
//    
//    UIImageView *animation = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 60, 60)];
//    animation.image = [UIImage imageNamed:@"hud_waiting_animation_white"];
//    
//    [waiting addSubview:animation];
//    
//    UIImageView *logo = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 60, 60)];
//    logo.image = [UIImage imageNamed:@"hud_waiting_logo"];
//    
//    [waiting addSubview:logo];
//    
//    hud.customView = waiting;
//    
//    /**
//     *  动画显示
//     */
//    CABasicAnimation* rotationAnimation;
//    rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
//    rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 2.0 ];
//    rotationAnimation.duration = 1;
//    rotationAnimation.cumulative = YES;
//    rotationAnimation.repeatCount = HUGE_VALF;
//    [animation.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
//    
//    hud.removeFromSuperViewOnHide = YES;
    
    [hud show:YES];
    
}

/**
 *  提示成功消息
 *
 *  @param title    内容
 *  @param view     父视图
 *  @param interval 显示时间
 */
+(void) showSuccessHUD:(NSString *)title AddedTo:(UIView *)view interval:(int)interval {
    
    [LYUtil hideHUDTo:view];
    [LYUtil showHUD:title AddedTo:view interval:interval];
    
//    MBProgressHUD *hud =[MBProgressHUD showHUDAddedTo:view animated:YES];
//    hud.color = kHUDColor;
//    hud.margin = 10;
//    hud.labelColor = RGBA(255, 255, 255, 1.0);
//    hud.labelFont = [UIFont systemFontOfSize:16];
//    
//    hud.mode = MBProgressHUDModeCustomView;
//    hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"37x-success"]];
//    if ([title length]>0) {
//        hud.labelText = title;
//    }
//    //    if ([detail length]>0) {
//    //        hud.detailsLabelText = detail;
//    //    }
//    hud.removeFromSuperViewOnHide = YES;
//    if (interval>0) {
//        [hud hide:YES afterDelay:interval];
//    } else {
//        [hud show:YES];
//    }
    
}

/**
 *  提示失败消息
 *
 *  @param title    内容
 *  @param view     父视图
 *  @param interval 显示时间
 */
+(void) showFailedHUD:(NSString *)title AddedTo:(UIView *)view interval:(int)interval {
    
    [LYUtil hideHUDTo:view];
    if ([LYUtil isNilOrEmpty:title]) {
        return;
    }
    [LYUtil showHUD:title AddedTo:view interval:interval];
    
//    MBProgressHUD *hud =[MBProgressHUD showHUDAddedTo:view animated:YES];
//    hud.color = kHUDColor;
//    hud.margin = 10;
//    hud.labelColor = RGBA(255, 255, 255, 1.0);
//    hud.labelFont = [UIFont systemFontOfSize:16];
//    
//    hud.mode = MBProgressHUDModeCustomView;
//    hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"37x-failed"]];
//    if ([title length]>0) {
//        hud.labelText = title;
//    }
//    //    if ([detail length]>0) {
//    //        hud.detailsLabelText = detail;
//    //    }
//    hud.removeFromSuperViewOnHide = YES;
//    if (interval>0) {
//        [hud hide:YES afterDelay:interval];
//    } else {
//        [hud show:YES];
//    }
    
}

/**
 *  提示警告消息
 *
 *  @param title    内容
 *  @param view     父视图
 *  @param interval 显示时间
 */
+(void) showWarningHUD:(NSString *)title AddedTo:(UIView *)view interval:(int)interval {
    
    [LYUtil hideHUDTo:view];
    [LYUtil showHUD:title AddedTo:view interval:interval];
//    MBProgressHUD *hud =[MBProgressHUD showHUDAddedTo:view animated:YES];
//    hud.mode = MBProgressHUDModeCustomView;
//    hud.color = [UIColor clearColor];
//    
//    UILabel *titleView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 170, 50)];
//    titleView.backgroundColor = kHUDColor;
//    titleView.font = [UIFont systemFontOfSize:13];
//    titleView.textColor = [UIColor whiteColor];
//    titleView.textAlignment = NSTextAlignmentCenter;
//    titleView.layer.cornerRadius = 3;
//    titleView.layer.masksToBounds = YES;
//    
//    hud.customView = titleView;
//    
//    if ([title length]>0) {
//        titleView.text = title;
//    }
//    
//    hud.removeFromSuperViewOnHide = YES;
//    if (interval>0) {
//        [hud hide:YES afterDelay:interval];
//    } else {
//        [hud show:YES];
//    }
    
}

+(void) showHUD:(NSString *)title AddedTo:(UIView *)view interval:(int)interval {
    
    [LYUtil hideHUDTo:view];
    
    MBProgressHUD *hud =[MBProgressHUD showHUDAddedTo:view animated:YES];
    hud.mode = MBProgressHUDModeCustomView;
    hud.color = [UIColor clearColor];
    
    CGFloat titleW = 170;
    if (title) {
        titleW = [LYUtil sizeWithText:title font:[UIFont systemFontOfSize:13] withHeight:50].width+20;
    }
    UILabel *titleView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, titleW, 50)];
    titleView.backgroundColor = kHUDColor;
    titleView.font = [UIFont systemFontOfSize:13];
    titleView.textColor = [UIColor whiteColor];
    titleView.textAlignment = NSTextAlignmentCenter;
    titleView.layer.cornerRadius = 3;
    titleView.layer.masksToBounds = YES;
    
    hud.customView = titleView;
    
    if (title != nil && [title length]>0) {
        titleView.text = title;
    }
    
    hud.removeFromSuperViewOnHide = YES;
    if (interval>0) {
        [hud hide:YES afterDelay:interval];
    } else {
        [hud show:YES];
    }
}

/**
 *  消息发送成功
 *
 *  @param title    内容
 *  @param view     父视图
 *  @param interval 显示时间
 */
+(void) showSuccessHUDWithMsg:(NSString *)title AddedTo:(UIView *)view interval:(int)interval{
    
    [LYUtil hideHUDTo:view];
    
    MBProgressHUD *hud =[MBProgressHUD showHUDAddedTo:[[UIApplication sharedApplication] delegate].window animated:YES];
    hud.color = kHUDColor;
    hud.margin = 10;
    hud.labelColor = [UIColor redColor];
    hud.labelFont = [UIFont systemFontOfSize:15];
    hud.dimBackground = YES;
    
    hud.mode = MBProgressHUDModeText;
    
    if ([title length]>0) {
        hud.labelText = title;
    }
    hud.removeFromSuperViewOnHide = YES;
    if (interval>0) {
        [hud hide:YES afterDelay:interval];
    } else {
        [hud show:YES];
    }
}

/**
 *  隐藏
 *
 *  @param view 父视图
 */
+(void) hideHUDTo:(UIView *)view {
    
    [MBProgressHUD hideAllHUDsForView:view animated:YES];
    
}

/**
 *  计算文本高度
 *
 *  @param text     文本内容
 *  @param font     字体大小
 *  @param maxWidth 最大宽度
 *
 *  @return 文本大小
 */
+ (CGSize)sizeWithText:(NSString*)text font:(UIFont*)font withWidth:(float)maxWidth {
    
    CGSize maxSize = CGSizeMake(maxWidth, CGFLOAT_MAX);
    
    CGSize textSize = CGSizeZero;
    // iOS7以后使用boundingRectWithSize，之前使用sizeWithFont
    if ([text respondsToSelector:@selector(boundingRectWithSize:options:attributes:context:)]) {
        // 多行必需使用NSStringDrawingUsesLineFragmentOrigin，网上有人说不是用NSStringDrawingUsesFontLeading计算结果不对
        NSStringDrawingOptions opts = NSStringDrawingUsesLineFragmentOrigin |
        NSStringDrawingUsesFontLeading;
        
        NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
        [style setLineBreakMode:NSLineBreakByCharWrapping];
        
        NSDictionary *attributes = @{ NSFontAttributeName : font, NSParagraphStyleAttributeName : style };
        
        CGRect rect = [text boundingRectWithSize:maxSize
                                         options:opts
                                      attributes:attributes
                                         context:nil];
        textSize = rect.size;
    }
    else{
        textSize = [text sizeWithFont:font constrainedToSize:maxSize lineBreakMode:NSLineBreakByCharWrapping];
    }
    
    return textSize;
}

+ (CGSize)sizeWithText:(NSString*)text font:(UIFont*)font withHeight:(float)maxHeight {
    
    CGSize maxSize = CGSizeMake(CGFLOAT_MAX,maxHeight);
    
    CGSize textSize = CGSizeZero;
    // iOS7以后使用boundingRectWithSize，之前使用sizeWithFont
    if ([text respondsToSelector:@selector(boundingRectWithSize:options:attributes:context:)]) {
        // 多行必需使用NSStringDrawingUsesLineFragmentOrigin，网上有人说不是用NSStringDrawingUsesFontLeading计算结果不对
        NSStringDrawingOptions opts = NSStringDrawingUsesLineFragmentOrigin |
        NSStringDrawingUsesFontLeading;
        
        NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
        [style setLineBreakMode:NSLineBreakByCharWrapping];
        
        NSDictionary *attributes = @{ NSFontAttributeName : font, NSParagraphStyleAttributeName : style };
        
        CGRect rect = [text boundingRectWithSize:maxSize
                                         options:opts
                                      attributes:attributes
                                         context:nil];
        textSize = rect.size;
    }
    else{
        textSize = [text sizeWithFont:font constrainedToSize:maxSize lineBreakMode:NSLineBreakByCharWrapping];
    }
    
    return textSize;
}


+ (CGSize)sizeWithText:(NSString*)text font:(UIFont*)font width:(float)maxWidth lineSpacing:(float)lineSpacing{

    return [LYUtil sizeWithText:text font:font width:maxWidth lineSpacing:lineSpacing paragraphSpacing:0];
}

+ (CGSize)sizeWithText:(NSString*)text font:(UIFont*)font width:(float)maxWidth lineSpacing:(float)lineSpacing paragraphSpacing:(float)paragraphSpacing{
    
    CGSize maxSize = CGSizeMake(maxWidth, CGFLOAT_MAX);
    
    CGSize textSize = CGSizeZero;
    // iOS7以后使用boundingRectWithSize，之前使用sizeWithFont
    if ([text respondsToSelector:@selector(boundingRectWithSize:options:attributes:context:)]) {
        // 多行必需使用NSStringDrawingUsesLineFragmentOrigin，网上有人说不是用NSStringDrawingUsesFontLeading计算结果不对
        NSStringDrawingOptions opts = NSStringDrawingUsesLineFragmentOrigin |
        NSStringDrawingUsesFontLeading;
        
        NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
        if (lineSpacing > 0) {
            [style setLineSpacing:lineSpacing];
        }
        if (paragraphSpacing > 0) {
            [style setParagraphSpacing:paragraphSpacing];
        }
        [style setLineBreakMode:NSLineBreakByCharWrapping];
        if (font == nil) {
            font = [UIFont systemFontOfSize:[UIFont systemFontSize]];
        }
        NSDictionary *attributes = @{ NSFontAttributeName : font, NSParagraphStyleAttributeName : style };
        
        CGRect rect = [text boundingRectWithSize:maxSize
                                         options:opts
                                      attributes:attributes
                                         context:nil];
        textSize = rect.size;
    }
    else{
        textSize = [text sizeWithFont:font constrainedToSize:maxSize lineBreakMode:NSLineBreakByCharWrapping];
    }
    
    return textSize;
}

/**
 *  创建sign
 *
 *  @return
 */
+ (NSString *) createSign:(NSString *)TIMESTAMP{
    
    NSString *APPVER = kAPPVER;
    NSString *PL = kPL;
    NSString *sign = [NSString md5:[NSString stringWithFormat:@"APPVER=%@&PL=%@&TIMESTAMP=%@%@",APPVER,PL,TIMESTAMP,kSecret]];
   
    return sign;
}

+(NSString *)compareDate:(NSDate *)date{
    
    NSTimeInterval secondsPerDay = 24 * 60 * 60;
    NSDate *today = [[NSDate alloc] init];
    NSDate *tomorrow, *yesterday,*beforeDay;
    
    tomorrow = [today dateByAddingTimeInterval: secondsPerDay];
    yesterday = [today dateByAddingTimeInterval: -secondsPerDay];
    beforeDay = [today dateByAddingTimeInterval: -(2*secondsPerDay)];
    
    // 10 first characters of description is the calendar date:
    NSString * todayString = [[today description] substringToIndex:10];
    NSString * yesterdayString = [[yesterday description] substringToIndex:10];
    NSString * tomorrowString = [[tomorrow description] substringToIndex:10];
    NSString * beforeString = [[beforeDay description] substringToIndex:10];
    
    NSString * dateString = [[date description] substringToIndex:10];
    
    if ([dateString isEqualToString:todayString])
    {
        return @"今日";
    } else if ([dateString isEqualToString:yesterdayString])
    {
        return @"昨日";
    }else if ([dateString isEqualToString:beforeString])
    {
        return @"前日";
    }else if ([dateString isEqualToString:tomorrowString])
    {
        return @"明日";
    }
    else
    {
        return dateString;
    }
}
+ (NSString *)compareDateStr:(NSString *)dateStr
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyy-MM-dd HH:mm:ss";
   NSDate *date = [formatter dateFromString:dateStr];
    
    NSString *str = [self compareDate:date];
    if (str.length>2) {
        NSDateFormatter *formatter3 = [[NSDateFormatter alloc] init];
        formatter3.dateFormat = @"MM-dd ";
        str = [formatter3 stringFromDate:date];
    }
    str = [str stringByReplacingOccurrencesOfString:@"今日" withString:@""];
    str = [str stringByReplacingOccurrencesOfString:@"昨日" withString:@"昨日 "];
    str = [str stringByReplacingOccurrencesOfString:@"前日" withString:@"前日 "];
    
    NSDateFormatter *formatter2 = [[NSDateFormatter alloc] init];
    formatter2.dateFormat = @"HH:mm";
    NSString *str2 = [formatter2 stringFromDate:date];
    return [NSString stringWithFormat:@"%@%@",str,str2];
}
+(void) showLongTextFailedHUD:(NSString *)title AddedTo:(UIView *)view interval:(int)interval
{
    
    [LYUtil hideHUDTo:view];
    
    MBProgressHUD *hud =[MBProgressHUD showHUDAddedTo:view animated:YES];
    hud.mode = MBProgressHUDModeCustomView;
    hud.color = [UIColor clearColor];
    
    CGFloat titleW = 170;
    if (title) {
        titleW = [LYUtil sizeWithText:title font:[UIFont systemFontOfSize:13] withHeight:50].width+20;
    }
    UILabel *titleView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, titleW, 50)];
    titleView.backgroundColor = kHUDColor;
    titleView.font = [UIFont systemFontOfSize:13];
    titleView.textColor = [UIColor whiteColor];
    titleView.textAlignment = NSTextAlignmentCenter;
    titleView.layer.cornerRadius = 3;
    titleView.layer.masksToBounds = YES;
    titleView.numberOfLines = 0;
    
    hud.customView = titleView;
    
    if ([title length]>0) {
        titleView.text = title;
    }
    
    hud.removeFromSuperViewOnHide = YES;
    if (interval>0) {
        [hud hide:YES afterDelay:interval];
    } else {
        [hud show:YES];
    }

    
}

/**
 *  获取系统版本号
 *
 *  @return 版本号
 */
+ (NSString *) getDeviceInfo{
    
    NSString *deviceInfo = [NSString stringWithFormat:@"iOS %@",[[UIDevice currentDevice] systemVersion]];
    
    return  deviceInfo;
}


/**
 *  等比缩放图片
 *
 *  @param size 当前图片大小
 *
 *  @return 缩放后大小
 */

+ (UIImage *)scaleToSize:(UIImage *)img size:(CGRect)size{
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    CGSize sSize = CGSizeMake(size.size.width, size.size.height);
    UIGraphicsBeginImageContext(sSize);
    // 绘制改变大小的图片
    [img drawInRect:CGRectMake(0, size.origin.y, size.size.width, size.size.height)];
    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    // 返回新的改变大小后的图片
    return scaledImage;
}
/**
 *  判断是否是合法的手机号
 *
 *  @param phone 手机号
 *
 *  @return 是否是合法标准的手机号
 */
+ (BOOL)isValidatePhone:(NSString *)phone
{
    if (phone == nil) {
        return NO;
    }
    
    if (phone.length == 11) {
        return YES;
    } else {
        return NO;
    }
    
//    NSString *phoneRegex = @"1[3|5|7|8|][0-9]{9}";
//    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneRegex];
//    return [phoneTest evaluateWithObject:phone];
}
/**
 *  判断是否是合法的验证码
 *
 *  @param phone 验证码
 *
 *  @return 是否是合法标准的验证码
 */
+ (BOOL)isValidateSmsCode:(NSString *)smsCode
{
    if (smsCode == nil) {
        return NO;
    }
    // 目前验证码是4位数字
    NSString *smsCodeRegex = @"[0-9]{4}";
    NSPredicate *smsCodeTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", smsCodeRegex];
    return [smsCodeTest evaluateWithObject:smsCode];
}
/**
 *  判断是否是合法的密码
 *
 *  @param phone 密码
 *
 *  @return 是否是合法标准的密码
 */
+ (BOOL)isValidatePassword:(NSString *)password
{
    if (password == nil) {
        return NO;
    }
    //6-16位数字和字母组成
    NSString *regex = @"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    if ([pred evaluateWithObject:password]) {
        return YES ;
    }else{
      return NO;
    }
    
}
/**
 *  获取最新的用户信息
 */
+ (NSString *)putStarInMobile:(NSString *)mobile{
    if (mobile == nil) {
        return mobile;
    }
    if (mobile.length != 11) {
        return mobile;
    }
    NSString *preStr = [mobile substringToIndex:3];
    NSString *sufStr = [mobile substringFromIndex:7];
    return [NSString stringWithFormat:@"%@****%@",preStr,sufStr];
}
/**
 *  生产带高亮并且有连接的富文本
 *
 *  @param contentStr 原始文本 
 *  contentStr = @"前期提示的[link color=\"0190d9\" url=\"http:www.baidu.com\"]实达集团(600734)[/link]电视剧发皮带机发泡斯蒂芬金牌[link url=\"http:www.google.com\"]abc[/link]";
 *  @warning link url 是固定的，必须与后台一致
 *  @return 生产后的富文本
 */
+ (NSMutableAttributedString *)attributedStrWithString:(NSString *)contentStr defaultColor:(UIColor *)defaultColor
{
    LYLog(@"contentStr:%@",contentStr);
    // 穷举所有的标签
    NSArray *tags = @[@"url",@"URL",@"color",@"font",@"left",@"right",@"center",@"align",@"size",@"sub",@"sup",@"email",@"img"];
    
    BBCodeParser *parser = [[BBCodeParser alloc] initWithTags:tags];
    [parser setCode:contentStr];
    [parser parse];
    
    NSMutableArray *attrArrayM = [NSMutableArray array];
    // 将标签提取出来并将文本去标签组合
    if (parser.element.elements.count >0) {
        BBElement *parentElement = ((BBElement *)parser.element.elements.firstObject).parent;
        contentStr = parentElement.format;
        for (int i=0; i<parser.element.elements.count; i++) {
            BBElement *element = parser.element.elements[i];
            
            NSString *showText = element.text;
            NSString *placeStr = [NSString stringWithFormat:@"{BB_%ld_BB}",(long)i];
            NSRange range = [contentStr rangeOfString:placeStr];
            range.length = showText.length;
            
            
            NSMutableDictionary *dictM = [NSMutableDictionary dictionary];
            [attrArrayM addObject:dictM];
            
            // 1、范围
            dictM[@"range"] = [NSValue valueWithRange:range];
            
            // 2、颜色
//            UIColor *color = [UIColor colorWithHexString:[element attributeWithName:@"color"].value];
//            if (color == nil) {
//                color = [UIColor colorWithHexString:@"#4190d9"];
//            }
            // 3、URL
            if ([element.tag hasPrefix:@"url="] || [element.tag hasPrefix:@"URL="]) {
                NSString *urlStr = [element.tag componentsSeparatedByString:@"="].lastObject;
                NSURL *url = [NSURL URLWithString:urlStr];
                dictM[@"url"] = url;
            }
            // 4...n 穷举各种可能
            
            contentStr = [contentStr stringByReplacingOccurrencesOfString:placeStr withString:showText];
        }
    }
    
    return [self attbuteStringWithContentStr:contentStr attrArray:attrArrayM defaultColor:defaultColor];
}
/**
 *  将文本信息和富文本设计合成富文本信息
 *
 *  @param contentStr 文本信息
 *  @param attrArray  文本描述
 *
 *  @return 富文本信息
 */
+ (NSMutableAttributedString *)attbuteStringWithContentStr:(NSString *)contentStr attrArray:(NSArray *)attrArray defaultColor:(UIColor *)defaultColor
{
    // 创建富文本信息
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:contentStr];
    
    // 设置默认颜色
    if (defaultColor != nil) {
        [attributedString addAttribute:NSForegroundColorAttributeName value:defaultColor range:NSMakeRange(0,contentStr.length)];
    }
    
    // 将标签显示在富文本上
    for (NSDictionary *dict in attrArray) {
        // 获取范围
        NSRange range = ((NSValue *)dict[@"range"]).rangeValue;
        
        // 1、颜色
        UIColor *color = dict[@"color"];
        // 设置高亮文字显示的颜色
        if (color != nil) {
            [attributedString addAttribute:NSForegroundColorAttributeName value:color range:range];
        }
        
        
        // 2、URL
        NSURL *url = dict[@"url"];
        // 设置高亮文字跳转的URL
        if (url != nil) {
            [attributedString addAttribute:NSLinkAttributeName value:url range:range];
            [attributedString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:range];
        }
        
        
        // 3、穷举其他可能类型
    }
    
    return attributedString;
}
/**
 *  将iPhone5s的对应高度的长度根据屏幕高度的比例转成对应屏幕的高度
 *
 *  @param value iPhone5s的高度
 *
 *  @return 根据屏幕比例的高度
 */
+ (CGFloat)getScreenScaleValueFromIphone5sValue:(CGFloat)value
{
    CGFloat iPhone5sHeight = 568.0f;
    CGFloat scaleHeight = (SCREEN_HEIGHT*value)/iPhone5sHeight;
    return scaleHeight;
}
+ (NSString *)getZmTimeWithDateStr:(NSString *)dateStr
{
    // 今天
    NSDate *today = [NSDate date];
    // 昨天
    NSDate *yesterday = [NSDate dateWithTimeInterval:-24*60*60 sinceDate:today];
    // 前天
    NSDate *dayBeforeYesterday = [NSDate dateWithTimeInterval:-24*60*60*2 sinceDate:today];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *fromDate = [formatter dateFromString:dateStr];
    
    // 日期时间模式
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyyMMdd"];
    
    long long todayNumber = [dateFormatter stringFromDate:today].longLongValue;
    long long yesterdayNumber = [dateFormatter stringFromDate:yesterday].longLongValue;
    long long dayBeforeYesterdayNumber = [dateFormatter stringFromDate:dayBeforeYesterday].longLongValue;
    long long fromDayNumber = [dateFormatter stringFromDate:fromDate].longLongValue;
    
    // 时间模式
    NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
    // 小于前天
    if (fromDayNumber < dayBeforeYesterdayNumber) {
        [timeFormatter setDateFormat:@"MM-dd HH:mm"];
    }else if (fromDayNumber < yesterdayNumber){
        // 小于昨天，
        [timeFormatter setDateFormat:@"前天 HH:mm"];
//    }else if (fromDayNumber < todayNumber || [dateStr substringWithRange:NSMakeRange(11, 2)].integerValue < 14){
    }else if (fromDayNumber < todayNumber){
        // 小于今天，
        [timeFormatter setDateFormat:@"昨天 HH:mm"];
    }else{
        [timeFormatter setDateFormat:@"HH:mm"];
    }
    NSString *time = @"";
    if (dateStr != nil) {
        time = [timeFormatter stringFromDate:fromDate];
    }
    return time;
}
+ (BOOL)isQQInstalled
    {
        if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"mqq://"]]) {
            return YES;
        }

        return NO;
    }


/**
 处理deeplink
 
 @param deepLink 跳转的请求路径
 @param vc 从哪个VC跳转的
 */
+(BOOL)handleDeepLindUrl:(NSURL *)url{
   
    BOOL canHandle = NO;
    // 判断是否是本应用定义的deeplink
    if ([url.scheme.lowercaseString isEqualToString:kDeeplinkScheme]) {
        // kDeeplinkScheme.length 包含xxxx:
        // 去掉scheme的部分及冒号：，比如http://www.baidu.com?name=lv中的http,得到//www.baidu.com?name=lv
        NSString *query = [url.absoluteString substringFromIndex:kDeeplinkScheme.length+1];
        // 如果地址包含了//,则去掉//,得到www.baidu.com?name=lv
        NSArray *urlArr = [query componentsSeparatedByString:@"?"];
        NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
        if (urlArr.count == 2) {
            NSArray *paramsArr = [urlArr.lastObject componentsSeparatedByString:@"&"];
            for (NSString *keyValue in paramsArr) {
                NSArray *keyValueArr = [keyValue componentsSeparatedByString:@"="];
                if (keyValueArr.count == 2) {
                    parmas[keyValueArr.firstObject] = keyValueArr.lastObject;
                }
            }
        }
        query = urlArr.firstObject;
        if ([query hasPrefix:@"//"]) {
            query = [query substringFromIndex:2];
        }
        // 用/将url进行拆分，并获取最后一个，得到最终要跳转的地址
        NSString *page = [query componentsSeparatedByString:@"/"].lastObject;
        
        
        UITabBarController *mainVC = (UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
        
        // 如果rootViewController不是UITabBarController，则说明是在线上引导图阶段
        if (![mainVC isKindOfClass:[UITabBarController class]]) {
            return YES;
        }
        
        // 当前显示所在的navgationController
        __block UINavigationController *nav = (UINavigationController *)mainVC.selectedViewController;
        // 正在显示controller
        UIViewController *currentVC = nav.viewControllers.lastObject;
        // 比较deeplink
        // 进入首页
        if ([page.lowercaseString isEqualToString:@"home"])
        {
            if (mainVC.selectedIndex == kTabIndexHome) {
                if (nav.childViewControllers.count>1) {
                    [nav popToRootViewControllerAnimated:YES];
                }else{
                    // 当前页面正是名师看盘页面
                }
            }else{
                mainVC.selectedIndex = kTabIndexHome;
                [nav popToRootViewControllerAnimated:NO];
            }
        }
        // 进入视频解盘
        else if ([page.lowercaseString isEqualToString:@"video"])
        {
            if (![mainVC.selectedViewController.childViewControllers.lastObject isKindOfClass:[LYVedioLiveController class]]) {
                LYVedioLiveController *vc = [LYVedioLiveController new];
                vc.hidesBottomBarWhenPushed = YES;
                UINavigationController *nav = mainVC.selectedViewController;
                [nav pushViewController:vc animated:YES];
            }
        }
//        //股票看板
//        else if ([page.lowercaseString isEqualToString:@"stock"]){
//
//            LYStockListController *vc = (LYStockListController *)currentVC;
//            if ([vc isKindOfClass:[LYStockListController class]]) {
//                return YES;
//            }else{
//                vc = [[LYStockListController alloc] initWithNibName:@"LYStockListController" bundle:nil];
//                NSNumber *idNumber = parmas[@"id"];
//                vc.teacher_id = idNumber;
//                vc.hidesBottomBarWhenPushed = YES;
//                [nav pushViewController:vc animated:YES];
//            }
//        }
        // 进入诊股/加战队
        else if ([page.lowercaseString isEqualToString:@"openim"])
        {
           
            LYNTESController *vc = (LYNTESController *)currentVC;
            if ([vc isKindOfClass:[LYNTESController class]]) {
                return YES;
            }else{
                vc = [[LYNTESController alloc] initWithNibName:@"LYNTESController" bundle:nil];
                vc.hidesBottomBarWhenPushed = YES;
                [nav pushViewController:vc animated:YES];
            }
        }
        // 进入我的
        else if ([page.lowercaseString isEqualToString:@"mine"])
        {
            if (mainVC.selectedIndex == kTabIndexMine) {
                if (nav.childViewControllers.count>1) {
                    [nav popToRootViewControllerAnimated:YES];
                }else{
                    // 当前页面正是我的页面
                }
            }else{
                mainVC.selectedIndex = kTabIndexMine;
                [nav popToRootViewControllerAnimated:NO];
            }
        }
        // 进入视频列表
        else if ([page.lowercaseString isEqualToString:@"videolist"])
        {
            WatchPlayBackViewController *vedioDetailVC = (WatchPlayBackViewController *)currentVC;
            if ([vedioDetailVC isKindOfClass:NSClassFromString(@"WatchPlayBackViewController")]) {
                return YES;
            }else{
                vedioDetailVC = [WatchPlayBackViewController new];
                vedioDetailVC.hidesBottomBarWhenPushed = YES;
                LYPlaybackModel *playModel = [LYPlaybackModel new];
                playModel.vurl = parmas[@"url"];
                vedioDetailVC.playModel = playModel;
                [nav pushViewController:vedioDetailVC animated:YES];
            }
        }
        // 进入消息中心
        else if ([page.lowercaseString isEqualToString:@"msgcenter"])
        {
            LYMessageCenterController *vc = (LYMessageCenterController *)currentVC;
            if ([vc isKindOfClass:[LYMessageCenterController class]]) {
                return YES;
            }else{
                if (![LYLocalData sharedInstance].isUserLogined) {
                    [LYUtil showFailedHUD:@"还未登录,请先登录" AddedTo:MAIN_WINDOW interval:1.5];
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [LYLoginNewController taskAfterLogin:^{
                            LYMessageCenterController *vc = [[LYMessageCenterController alloc] init];
                            vc.hidesBottomBarWhenPushed = YES;
                            [nav pushViewController:vc animated:YES];
                        }];
                        
                    });
                    return YES;;
                }
                vc = [[LYMessageCenterController alloc] init];
                vc.hidesBottomBarWhenPushed = YES;
                [nav pushViewController:vc animated:YES];
            }
        }
        // 进入老师列表
        else if ([page.lowercaseString isEqualToString:@"masters"])
        {
            LYAllTeacherController *vc = (LYAllTeacherController *)currentVC;
            if ([vc isKindOfClass:[LYAllTeacherController class]]) {
                return YES;
            }else{
                vc = [[LYAllTeacherController alloc] init];
                vc.hidesBottomBarWhenPushed = YES;
                [nav pushViewController:vc animated:YES];
            }
        }
        // 进入老师详情
        else if ([page.lowercaseString isEqualToString:@"masterdetail"])
        {
            LYTeacherHomePageController *vc = (LYTeacherHomePageController *)currentVC;
            if ([vc isKindOfClass:[LYTeacherHomePageController class]]) {
                return YES;
            }else{
                vc = [[LYTeacherHomePageController alloc] init];
                NSNumber *teacherId = parmas[@"id"];
                vc.teacherId = teacherId.integerValue;
                vc.hidesBottomBarWhenPushed = YES;
                [nav pushViewController:vc animated:YES];
            }
        }
        // 进入名师看盘详情
        else if ([page.lowercaseString isEqualToString:@"textdetail"])
        {
            HomeHotArticleModel *model = [HomeHotArticleModel new];
            model.lm_id = parmas[@"id"];;
            LYArticleDetailController *imageTextDetail =  [[LYArticleDetailController alloc] init];
            imageTextDetail.model = model;
            imageTextDetail.isComment = NO;
         
            imageTextDetail.hidesBottomBarWhenPushed = YES;
            [nav pushViewController:imageTextDetail animated:YES];

        }
        //进入览益头条详情
        else if ([page.lowercaseString isEqualToString:@"topdetail"])
        {
                LYHomeInforDetailController *detailVC = [[LYHomeInforDetailController alloc] initWithNibName:@"LYHomeInforDetailController" bundle:nil];
                NSString *lmId = parmas[@"id"];
                HomeHotArticleModel *model = [HomeHotArticleModel new];
                model.lm_id = lmId;
                [detailVC setValue:model forKey:@"model"];
                detailVC.hidesBottomBarWhenPushed = YES;
                detailVC.isLanyiTop = YES;
                [LYLocalData sharedInstance].beforeTabIndex = 0;
                [nav pushViewController:detailVC animated:YES];
        }
        //进入市场快讯详情
        else if ([page.lowercaseString isEqualToString:@"flashdetail"])
        {
                LYHomeInforDetailController *detailVC = [[LYHomeInforDetailController alloc] initWithNibName:@"LYHomeInforDetailController" bundle:nil];
                NSString *lmId = parmas[@"id"];
                HomeHotArticleModel *model = [HomeHotArticleModel new];
                model.lm_id = lmId;
                [detailVC setValue:model forKey:@"model"];
                detailVC.hidesBottomBarWhenPushed = YES;
                [LYLocalData sharedInstance].beforeTabIndex = 0;
                [nav pushViewController:detailVC animated:YES];
        }
        
        // 进入视频回放
        else if ([page.lowercaseString isEqualToString:@"videolist"])
        {
            WatchPlayBackViewController *vedioDetailVC = (WatchPlayBackViewController *)currentVC;
            if ([vedioDetailVC isKindOfClass:NSClassFromString(@"WatchPlayBackViewController")]) {
                return YES;
            }else{
                vedioDetailVC = [WatchPlayBackViewController new];
                vedioDetailVC.hidesBottomBarWhenPushed = YES;
                LYPlaybackModel *model = [LYPlaybackModel new];
                model.vurl = parmas[@"url"];
                [nav pushViewController:vedioDetailVC animated:YES];
            }
        }
        // 进入投诉建议
        else if ([page.lowercaseString isEqualToString:@"feedback"])
        {
            LYFeedBackController *feedbackVC = (LYFeedBackController *)currentVC;
            if ([feedbackVC isKindOfClass:NSClassFromString(@"LYFeedBackController")]) {
                return YES;
            }else{
                feedbackVC = [[LYFeedBackController alloc] init];
                feedbackVC.hidesBottomBarWhenPushed = YES;
                [nav pushViewController:feedbackVC animated:YES];
            }
            
        }
        // 进入使用帮助
        else if ([page.lowercaseString isEqualToString:@"help"])
        {
            LYWebController *webVC = (LYWebController *)currentVC;
            if ([webVC isKindOfClass:NSClassFromString(@"LYWebController")] && [@"使用帮助" isEqual:webVC.navTitle]) {
                return YES;
            }else{
                LYWebController *useHelpVC = [[LYWebController alloc] initWithNibName:@"LYWebController" bundle:nil];
                useHelpVC.webUrl =  kLYUseGuideUrl;// kLYUseGuideUrl_HTTPS;
                useHelpVC.navTitle = @"使用帮助";
                useHelpVC.hidesBottomBarWhenPushed = YES;
                [nav pushViewController:useHelpVC animated:YES];
            }
        }
        // 进入免责声明
        else if ([page.lowercaseString isEqualToString:@"disclaimer"])
        {
            LYWebController *webVC = (LYWebController *)currentVC;
            if ([webVC isKindOfClass:NSClassFromString(@"LYWebController")] && [@"免责声明" isEqual:webVC.navTitle]) {
                return YES;
            }else{
                LYWebController *disclaimerVC = [[LYWebController alloc] initWithNibName:@"LYWebController" bundle:nil];
                disclaimerVC.webUrl = kLYDisclaimerUrl_HTTPS;
                disclaimerVC.navTitle = @"免责声明";
                disclaimerVC.hidesBottomBarWhenPushed = YES;
                [nav pushViewController:disclaimerVC animated:YES];
            }
        }
        // 进入web
        else if ([page.lowercaseString isEqualToString:@"web"])
        {
            LYWebController *webVC = (LYWebController *)currentVC;
            if ([webVC isKindOfClass:NSClassFromString(@"LYWebController")]) {
                return YES;
            }else{
                LYWebController *disclaimerVC = [[LYWebController alloc] initWithNibName:@"LYWebController" bundle:nil];
                if (url.absoluteString.length > 17) {
                    disclaimerVC.webUrl = [url.absoluteString substringFromIndex:17];
                }
                disclaimerVC.hidesBottomBarWhenPushed = YES;
                [nav pushViewController:disclaimerVC animated:YES];
            }
        }
        else if ([page.lowercaseString isEqualToString:@"quote"])
        {
            LYStockDetailController *stockDetail = [[LYStockDetailController alloc] initWithNibName:@"LYStockDetailController" bundle:nil];
            NSString *ngwId = parmas[@"ngwId"];
            if ([ngwId isEqualToString:@"2318"]||[ngwId isEqualToString:@"2185"]||[ngwId isEqualToString:@"2121"]) {
                stockDetail.isZSData = YES;
            } else {
                stockDetail.isZSData = NO;
            }
            stockDetail.innercode = parmas[@"ngwId"];
            stockDetail.hidesBottomBarWhenPushed = YES;
            [nav pushViewController:stockDetail animated:YES];

        } else if ([page.lowercaseString isEqualToString:@"trading"])
        {
            [nav popToRootViewControllerAnimated:YES];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                UITabBarController *mainVC = (UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
                mainVC.selectedIndex = 3;
                __block UINavigationController *nav = (UINavigationController *)mainVC.selectedViewController;
                for (UIViewController *viewController in nav.viewControllers) {
                    if ([viewController isKindOfClass:[LYNewQuotationController class]]) {
                        LYNewQuotationController *quotationVC = (LYNewQuotationController *)viewController;
                        [quotationVC resetScrollViewContentOffsetX];
                    }
                }
            });
        }

        // 登录
        else if ([page.lowercaseString isEqualToString:@"login"])
        {
            LYLoginNewController *loginVC = (LYLoginNewController *)currentVC;
            if ([loginVC isKindOfClass:NSClassFromString(@"LYLoginNewController")]) {
                return YES;
            }else{
                [LYLoginNewController taskAfterLogin:^{
                    
                }];
            }
        } else if ([page.lowercaseString isEqualToString:@"sign"])
        {
            
            LYSignInPopView *signPopView = [LYSignInPopView viewWithXib];
            signPopView.isDeepLink = YES;
            [signPopView showInWindow];
        }
        canHandle = YES;
    }
    else {
        UITabBarController *mainVC = (UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
        __block UINavigationController *nav = (UINavigationController *)mainVC.selectedViewController;
        LYWebController *webVC = [[LYWebController alloc] initWithNibName:@"LYWebController" bundle:nil];
        webVC.webUrl = url.absoluteString;
        webVC.hidesBottomBarWhenPushed = YES;
        [nav pushViewController:webVC animated:YES];
        canHandle = YES;
    }
    return canHandle;
}
/**
 给属性字体设置行间距，也就是两行字中间的空白距离
 
 @param attrStr 需要设置的属性文本
 @param lineSpace 行间距大小
 */
+(void)addLineSpaceWithMutableAttbuteString:(NSMutableAttributedString *)attrStr lineSpace:(CGFloat)lineSpace{
    // 设置行间距
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:lineSpace];
    [attrStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [attrStr  length])];
}
/**
 给属性字体设置字间距，也就是两个字中间的空白距离
 
 @param attrStr 需要设置的属性文本
 @param characterSpace 字间距大小
 */
+(void)addCharacterSpaceWithMutableAttbuteString:(NSMutableAttributedString *)attrStr characterSpace:(CGFloat)characterSpace{
    [attrStr addAttribute:NSKernAttributeName value:@(characterSpace) range:NSMakeRange(0,[attrStr length])];

}
/**
 给股票文本添加高亮颜色
 
 @param attrStr 需要设置的属性文本
 @param hightArray 需要高亮显示文本
 */
+(void)addStockHightColorWithMutableAttbuteString:(NSMutableAttributedString *)attrStr hightArray:(NSArray *)hightArray{
    NSString *text = attrStr.string;
    for (NSString *str in hightArray) {
        NSRange range = [text rangeOfString:str];
        [attrStr addAttribute:NSForegroundColorAttributeName
                        value:RGB(78, 127, 221)
                        range:range];
        
    }
}
+(NSString *)textString:(NSString *)text addTailText:(NSString *)tail font:(UIFont *)font maxLine:(NSInteger)maxLine maxWidth:(CGFloat)maxWidth
{
    CGFloat maxHeight = [font lineHeight]*maxLine;
    NSString *formatStr = [NSString stringWithFormat:@"%@",text];
    CGFloat height = [LYUtil sizeWithText:formatStr font:font withWidth:maxWidth].height;
    // -----小于最大行数的情况 快捷键为yy
    if (height<maxHeight) {
        formatStr = [NSString stringWithFormat:@"%@%@",text,tail];
        // 加上后缀后的高度
        CGFloat tailHeight = [LYUtil sizeWithText:formatStr font:font withWidth:maxWidth].height;
        // 如果加了结尾处的文字后会折行，则先用空格将最后一行填满，再下一行显示结尾字符串
        if (tailHeight>height) {
            NSString *emptyStr = @" ";
            formatStr = [NSString stringWithFormat:@"%@%@",emptyStr,text];
            // 用空字符串填满一行
            while ([LYUtil sizeWithText:formatStr font:font withWidth:maxWidth].height<=height) {
                emptyStr = [NSString stringWithFormat:@" %@",emptyStr];
                formatStr = [NSString stringWithFormat:@"%@%@",emptyStr,text];
            }
            text = [NSString stringWithFormat:@"%@%@%@",text,[emptyStr substringFromIndex:1],tail];
            
            return text;
        }else if (tailHeight == height) { // 当加上结尾数据也不满时，则在结尾数据前添加空字符
            NSString *emptyStr = @" ";
            formatStr = [NSString stringWithFormat:@"%@%@%@",text,emptyStr,tail];
            // 用空字符串填满一行
            while ([LYUtil sizeWithText:formatStr font:font withWidth:maxWidth].height<=height) {
                emptyStr = [NSString stringWithFormat:@"%@ ",emptyStr];
                formatStr = [NSString stringWithFormat:@"%@%@%@",text,emptyStr,tail];
            }
            text = [NSString stringWithFormat:@"%@%@%@",text,[emptyStr substringFromIndex:1],tail];
            return text;
        }
    }else if(height == maxHeight){
        // -----刚好是最大行数的情况 快捷键为yy
        formatStr = [NSString stringWithFormat:@"%@%@",text,tail];
        // 加上后缀后的高度
        CGFloat tailHeight = [LYUtil sizeWithText:formatStr font:font withWidth:maxWidth].height;
        // 加上尾部文字就超过最大行了
        if (tailHeight > height) {
            text = [text substringToIndex:text.length-1];
            formatStr = [NSString stringWithFormat:@"%@...%@",text,tail];
            while ([LYUtil sizeWithText:formatStr font:font withWidth:maxWidth].height > height) {
                text = [text substringToIndex:text.length-1];
                formatStr = [NSString stringWithFormat:@"%@...%@",text,tail];
            }
            text = [NSString stringWithFormat:@"%@...%@",text,tail];
            return text;
        }else{
            NSString *emptyStr = @" ";
            formatStr = [NSString stringWithFormat:@"%@%@%@",text,emptyStr,tail];
            // 用空字符串填满一行
            while ([LYUtil sizeWithText:formatStr font:font withWidth:maxWidth].height<=height) {
                emptyStr = [NSString stringWithFormat:@"%@ ",emptyStr];
                formatStr = [NSString stringWithFormat:@"%@%@%@",text,emptyStr,tail];
            }
            text = [NSString stringWithFormat:@"%@%@%@",text,[emptyStr substringFromIndex:1],tail];
            return text;
        }
    }else{
        text = [text substringToIndex:text.length-2];
        formatStr = [NSString stringWithFormat:@"%@...%@",text,tail];
        while ([LYUtil sizeWithText:formatStr font:font withWidth:maxWidth].height > maxHeight) {
            text = [text substringToIndex:text.length-2];
            formatStr = [NSString stringWithFormat:@"%@...%@",text,tail];
        }
        text = [NSString stringWithFormat:@"%@...%@",text,tail];
        return text;
    }
    return nil;
}

+ (void)addSensorsTrack:(NSString *)track Properties:(NSDictionary *)properties {
    
    [[SensorsAnalyticsSDK sharedInstance] track:track
                                 withProperties:properties];
}

+ (NSString *)returnCurrentTime {
    
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
    NSString *dateTime = [formatter stringFromDate:date];
    return dateTime;
}

+ (NSString *)returnTimeWithFormat:(NSString *)format {
   
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:format];
    NSString *dateTime = [formatter stringFromDate:date];
    return dateTime;
}

#pragma mark - 将某个时间戳转化成 时间

+(NSString *)timestampSwitchTime:(NSInteger)timestamp andFormatter:(NSString *)format{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:format]; // （@"YYYY-MM-dd hh:mm:ss"）----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    [formatter setTimeZone:timeZone];
    NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:timestamp];
    NSString *confromTimespStr = [formatter stringFromDate:confromTimesp];
    return confromTimespStr;
}

+(NSString *)lySensorsString:(NSString *)string {
    
    if (string == nil || string == NULL) {
        return @"Ndata";
    }
    if ([string isKindOfClass:[NSNull class]]) {
        return @"Ndata";
    }
    if ([string isKindOfClass:[NSString class]] && [[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
        return @"Ndata";
    }
    return string;
}

//对网址和参数进行拼接,方便展示带有参数的网址,用于测试或者浏览器直接打开
+(NSString *)urlDictToStringWithUrlStr:(NSString *)urlStr Parameters:(NSDictionary *)parameters
{
    if (!parameters) {
        return urlStr;
    }
    
    
    NSMutableArray *parts = [NSMutableArray array];
    //便利参数,将key和value 进行拼接
    [parameters enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        //接收key
        if ([key isKindOfClass:[NSNumber class]]) {
            key = [NSString stringWithFormat:@"%@",key];
        }
        if ([obj isKindOfClass:[NSNumber class]]) {
            obj = [NSString stringWithFormat:@"%@",obj];
        }
        NSString *finalKey = [key stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        //接收值
        NSString *finalValue = [obj stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        
        
        NSString *part =[NSString stringWithFormat:@"%@=%@",finalKey,finalValue];
        
        [parts addObject:part];
        
    }];
    
    NSString *queryString = [parts componentsJoinedByString:@"&"];
    
    queryString = queryString ? [NSString stringWithFormat:@"?%@",queryString] : @"";
    
    NSString *pathStr = [NSString stringWithFormat:@"%@%@",urlStr,queryString];
    
    return pathStr;
    
}

/**
 *  截取URL中的参数
 *
 *  @return NSMutableDictionary parameters
 */
+ (NSMutableDictionary *)getURLParameters:(NSString *)urlStr {
    
    // 查找参数
    NSRange range = [urlStr rangeOfString:@"?"];
    if (range.location == NSNotFound) {
        return nil;
    }
    
    // 以字典形式将参数返回
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    
    // 截取参数
    NSString *parametersString = [urlStr substringFromIndex:range.location + 1];
    
    // 判断参数是单个参数还是多个参数
    if ([parametersString containsString:@"&"]) {
        
        // 多个参数，分割参数
        NSArray *urlComponents = [parametersString componentsSeparatedByString:@"&"];
        
        for (NSString *keyValuePair in urlComponents) {
            // 生成Key/Value
            NSArray *pairComponents = [keyValuePair componentsSeparatedByString:@"="];
            NSString *key = [pairComponents.firstObject stringByRemovingPercentEncoding];
            NSString *value = [pairComponents.lastObject stringByRemovingPercentEncoding];
            
            // Key不能为nil
            if (key == nil || value == nil) {
                continue;
            }
            
            id existValue = [params valueForKey:key];
            
            if (existValue != nil) {
                
                // 已存在的值，生成数组
                if ([existValue isKindOfClass:[NSArray class]]) {
                    // 已存在的值生成数组
                    NSMutableArray *items = [NSMutableArray arrayWithArray:existValue];
                    [items addObject:value];
                    
                    [params setValue:items forKey:key];
                } else {
                    
                    // 非数组
                    [params setValue:@[existValue, value] forKey:key];
                }
                
            } else {
                
                // 设置值
                [params setValue:value forKey:key];
            }
        }
    } else {
        // 单个参数
        
        // 生成Key/Value
        NSArray *pairComponents = [parametersString componentsSeparatedByString:@"="];
        
        // 只有一个参数，没有值
        if (pairComponents.count == 1) {
            return nil;
        }
        
        // 分隔值
        NSString *key = [pairComponents.firstObject stringByRemovingPercentEncoding];
        NSString *value = [pairComponents.lastObject stringByRemovingPercentEncoding];
        
        // Key不能为nil
        if (key == nil || value == nil) {
            return nil;
        }
        
        // 设置值
        [params setValue:value forKey:key];
    }
    
    return params;
}

+ (UIViewController*) findBestViewController:(UIViewController*)vc {
    
    if (vc.presentedViewController) {
        // Return presented view controller
        return [self findBestViewController:vc.presentedViewController];
    } else if ([vc isKindOfClass:[UISplitViewController class]]) {
        // Return right hand side
        UISplitViewController* svc = (UISplitViewController*) vc;
        if (svc.viewControllers.count > 0)
            return [self findBestViewController:svc.viewControllers.lastObject];
        else
            return vc;
    } else if ([vc isKindOfClass:[UINavigationController class]]) {
        
        // Return top view
        UINavigationController* svc = (UINavigationController*) vc;
        if (svc.viewControllers.count > 0)
            return [self findBestViewController:svc.topViewController];
        else
            return vc;
        
    } else if ([vc isKindOfClass:[UITabBarController class]]) {
        
        // Return visible view
        UITabBarController* svc = (UITabBarController*) vc;
        if (svc.viewControllers.count > 0)
            return [self findBestViewController:svc.selectedViewController];
        else
            return vc;
        
    } else {
        
        // Unknown view controller type, return last child view controller
        return vc;
        
    }
    
}


@end


